#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实时监控系统
"""

import asyncio
import json
from typing import Dict, Any, List
from datetime import datetime

from app.core.database import SessionLocal
from app.models.stream import Stream
from app.services.stream_monitor import get_stream_monitor


class MonitorService:
    """实时监控服务"""
    
    def __init__(self):
        self.active_connections = set()
        self.running = False
        self.monitor_task = None
        self.update_interval = 2  # 2秒更新一次
        
    async def connect(self, websocket):
        """建立WebSocket连接"""
        await websocket.accept()
        self.active_connections.add(websocket)
        
    async def disconnect(self, websocket):
        """断开WebSocket连接"""
        if websocket in self.active_connections:
            self.active_connections.remove(websocket)
            
    async def broadcast(self, data: Dict[str, Any]):
        """广播消息给所有连接"""
        if not self.active_connections:
            return
            
        message = json.dumps(data)
        for connection in list(self.active_connections):
            try:
                await connection.send_text(message)
            except Exception:
                # 连接已断开，移除
                self.active_connections.discard(connection)
                
    async def start(self):
        """启动实时监控"""
        if self.running:
            return
            
        self.running = True
        self.monitor_task = asyncio.create_task(self._monitor_loop())
        
    async def stop(self):
        """停止实时监控"""
        if not self.running:
            return
            
        self.running = False
        
        if self.monitor_task:
            self.monitor_task.cancel()
            try:
                await self.monitor_task
            except asyncio.CancelledError:
                pass
            finally:
                self.monitor_task = None
                
    async def _monitor_loop(self):
        """监控循环"""
        while self.running:
            try:
                data = await self._collect_status()
                await self.broadcast(data)
                await asyncio.sleep(self.update_interval)
            except asyncio.CancelledError:
                break
            except Exception:
                await asyncio.sleep(self.update_interval)
                
    async def _collect_status(self) -> Dict[str, Any]:
        """收集系统状态"""
        try:
            # 获取流状态
            stream_monitor = get_stream_monitor()
            streams = await stream_monitor.get_streams_from_db()
            
            # 统计信息
            total_streams = len(streams)
            online_streams = len([s for s in streams if s.get("status") == "online"])
            offline_streams = len([s for s in streams if s.get("status") == "offline"])
            
            return {
                "timestamp": datetime.now().isoformat(),
                "streams": {
                    "total": total_streams,
                    "online": online_streams,
                    "offline": offline_streams,
                    "list": streams
                }
            }
            
        except Exception:
            return {
                "timestamp": datetime.now().isoformat(),
                "streams": {
                    "total": 0,
                    "online": 0,
                    "offline": 0,
                    "list": []
                }
            }


# 全局监控服务实例
_monitor_service = None

def get_monitor_service():
    """获取监控服务实例"""
    global _monitor_service
    if _monitor_service is None:
        _monitor_service = MonitorService()
    return _monitor_service

async def start_monitor_service():
    """启动监控服务"""
    service = get_monitor_service()
    await service.start()

async def stop_monitor_service():
    """停止监控服务"""
    service = get_monitor_service()
    await service.stop()